<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Mail;

class LoginController extends Controller
{
    //设置首页
    public function getIndex()
    {
    	return view('user.login');
    }

    //登录页
    public function postDologin(Request $request)
    {
    	// dd($request->all());
    	//检测用户名是否存在
    	$user = DB::table('user')->where('username',$request->input('username'))->first();
    	if(!empty($user)){
    		if(Hash::check($request->input('password'),$user->password)){
    			session(['id'=>$user->id]);
    			return redirect('/admin')->with('success','欢迎'.$user->username.'登录');
    		}else{
    			return back()->with('error','密码错误');
    		}	
    	}else{
    		return back()->with('error','用户不存在');
    	}
    }

    //后台用户退出
    public function getLogout()
    {
    	session()->forget('id');
    	return redirect('/admin/login')->with('error','请登录');
    }

    //前台用户登录
    public function getHomelogin()
    {
    	return view('homelog.homelogin');
    }
    //前台用户注册
    public function getHomelog()
    {
        return view('homelog.homelog');
    }
    //填入数据
    public function postDoregister(Request $request)
    {
    	// dd($request->all());
    	$this->validate($request, [
        'username' => 'required|regex:/\w{6,18}/',
        'password' => 'required|regex:/\w{6,18}/',
        'repassword' => 'required|same:password',
    	],[
    	'username.required' => '用户名不能为空',
    	'username.regex' => '用户名格式不正确',
    	'password.required' => '密码不能为空',
    	'password.regex' => '密码格式不正确',
    	'repassword.required' => '重复密码不能为空',
    	'repassword.same' => '重复密码格式不正确',
    	]);
    	// 获取其他数据
    	$data = $request->only(['username','password']);
    	// dd($data);
    	//随机token
    	$data['token'] = str_random(50);
    	//状态为1未激活
    	$data['status'] = 1;
    	//密码加密
    	$data['password'] = Hash::make($data['password']);
        // dd($data);
    	//数据插入
    	$id = DB::table('aduser')->insertGetId($data);
        $email = $request->input('email');
        // dd($id);
    	if($id){
    		//注册成功 邮箱验证
            $this->getSeedmail($id,$data['token'],$email);
            return view('homelog.success');
    	}else{
    		return back()->with('error','注册失败');
    	}	
    }

    public function getSeedmail($id,$token,$email)
    {
        $id = 1;$token = '12352131asd';$email='609094035@qq.com';
    //     Mail::raw('狗蛋网欢迎你注册请点击.即可获取大量资源...', function ($message) {
    //     //设置邮件标题
    //     $message->subject('激活邮件');
    //     //发送给谁
    //     $message->to('609094035@qq.com');
    // });
          Mail::send('email.email', ['id' => $id,'token'=>$token,'email'=>$email], function ($message) use ($email) {
            //当前的对象 发送给谁 发送的名字
            $message->to($email)->subject('注册账号激活邮件');
        });
        // echo '2222';
    }
    public function getJihuo(Request $request)
    {
        echo '欢迎激活';
    }
}
